package cn.school.demo.ui.article.entity

import android.annotation.SuppressLint
import android.graphics.Color
import android.net.http.SslError
import android.os.Build
import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.webkit.*
import android.widget.ImageView
import android.widget.TextView
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.core.view.ViewCompat.TYPE_NON_TOUCH
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import cn.school.demo.MyApplication
import cn.school.demo.R
import cn.school.demo.databinding.FragmentArticleEntityBinding
import cn.school.demo.pojo.Comment
import cn.school.demo.repository.AnswerRepository
import com.ajguan.library.EasyRefreshLayout
import com.blankj.utilcode.util.LogUtils
import com.google.android.material.appbar.AppBarLayout
import com.mylhyl.circledialog.CircleDialog
import java.time.LocalDateTime

class ArticleEntityFragment : Fragment() {

    private lateinit var viewModel: ArticleEntityViewModel
    private lateinit var binding: FragmentArticleEntityBinding

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        viewModel = ViewModelProvider(this).get(ArticleEntityViewModel::class.java)
        binding =
            DataBindingUtil.inflate(inflater, R.layout.fragment_article_entity, container, false)
        binding.lifecycleOwner = viewLifecycleOwner
        binding.vw = this
        /*
        * 功能:
        * 1. 是否为通知（即服务器发送到通知栏的文章），若是根据id请求，初始化界面，同时重置通知标签
        * 2. 不是通知（APP内已有的文章），判断文章实体是否为空，不空则初始化界面，为空则报错！
        * */
        if (MyApplication.isNotify) {
            viewModel.getArticleById().observe(viewLifecycleOwner) {
                MyApplication.article = it
                init()
                MyApplication.isNotify = false
                //MyApplication.pendingIntent = null
            }
        } else {
            MyApplication.article?.let {
                init()
            } ?: let {
                CircleDialog.Builder().setText("出现严重错误！").setNegative("取消") {
                    MyApplication.goto(
                        R.id.action_ArticleEntity_to_Article,
                        findNavController(),
                        parentFragmentManager
                    )
                }.show(parentFragmentManager)
            }
        }
        return binding.root
    }


    /*
    * 初始化界面，包括加载数据、页面更新等
    * */
    @SuppressLint("SetTextI18n", "UseCompatLoadingForDrawables", "NewApi", "NotifyDataSetChanged")
    private fun init() {
        MyApplication.systemBarSetting(MyApplication.DARK, requireActivity())
        binding.apply {
            articleEntityRecyclerViewNoData.visibility = View.GONE
            viewModel.saveArticleHitById()
            val article = MyApplication.article
            //LogUtils.e(article)
            articleEntityTitle.text = article?.articleName
            articleEntityTime.text =
                article?.releaseTime.toString().subSequence(0, 10)
            articleEntityText.apply {
                this@ArticleEntityFragment.initWebView(article!!.articleContent)
            }
            articleEntityTextAuthor.text = "来源：${article?.source}"
            articleEntityReadButton.text = "阅读 ${article?.hit}"
            articleEntityLikeButton.apply {
                text = "点赞"
                val d = resources.getDrawable(R.drawable.love_unselect, null)
                d.setBounds(0, 0, 50, 50)
                setCompoundDrawables(
                    null,
                    null,
                    d,
                    null
                )
            }
            articleEntityEasyRefreshLayout.apply {
                isEnablePullToRefresh = false
                addEasyEvent(object :
                    EasyRefreshLayout.EasyEvent {
                    override fun onRefreshing() {
                        binding.articleEntityEasyRefreshLayout.refreshComplete()
                    }

                    override fun onLoadMore() {
                        viewModel.nextPage()
                        viewModel.getNextCommentListById().observe(viewLifecycleOwner) {
                            if (it.size != 0) {
                                viewModel.addCommentList(it)
                                binding.articleEntityCommentIconNumber.text =
                                    if (binding.articleEntityCommentIconNumber.text.toString() == "100+" ||
                                        binding.articleEntityCommentIconNumber.text.toString() == "100"
                                    ) "100+"
                                    else (binding.articleEntityCommentIconNumber.text.toString()
                                        .toInt() + it.size).toString()
                                binding.articleEntityRecyclerView.adapter?.notifyDataSetChanged()
                            }
                            if (it.size < viewModel.size) {
                                binding.articleEntityEasyRefreshLayout.loadNothing()
                                binding.articleEntityRecyclerViewNoData.visibility = View.GONE
                            }
                        }
                        binding.articleEntityEasyRefreshLayout.loadMoreComplete()
                    }
                })
            }
        }
        viewModel.apply {
            saveBrowseInfo().observe(viewLifecycleOwner) {
                if (it) {
                    AnswerRepository().saveAnswerIntegral(
                        mapOf(
                            "sfNumber" to MyApplication.user!!.sfNumber,
                            "sign" to 2,
                            "subjectName" to "阅读文章"
                        )
                    ).observe(viewLifecycleOwner) {
                        if (it.success) {
                            MyApplication.user!!.totalIntegral += 1
                        }
                    }
                }
            }
            isCF().observe(viewLifecycleOwner) {
                updateFabulous(it["fabulous"]!!)
                updateCollect(it["collect"]!!)
            }
            isFabulous.observe(viewLifecycleOwner) {
                if (it) {
                    val d = resources.getDrawable(R.drawable.love_selected, null)
                    d.setBounds(0, 0, 50, 50)
                    binding.articleEntityLikeButton.setCompoundDrawables(null, null, d, null)
                } else {
                    val d = resources.getDrawable(R.drawable.love_unselect, null)
                    d.setBounds(0, 0, 50, 50)
                    binding.articleEntityLikeButton.setCompoundDrawables(null, null, d, null)
                }
            }
            isCollect.observe(viewLifecycleOwner) {
                if (it) {
                    binding.articleEntityCollection.setImageResource(R.drawable.collectived)
                } else {
                    binding.articleEntityCollection.setImageResource(R.drawable.collective)
                }
            }
            getCommentListById().observe(viewLifecycleOwner) {
                binding.articleEntityProgressBar.visibility = View.GONE
                LogUtils.d("我获得了评论列表")
                updateCommentList(it)
                binding.articleEntityRecyclerView.apply {
                    adapter?.notifyDataSetChanged() ?: let {
                        adapter = CommentAdapter(viewModel.commentList)
                        layoutManager = LinearLayoutManager(requireContext())
                    }
                }
                /**/
                binding.articleEntityCommentIconNumber.text =
                    if (viewModel.commentList.size <= 100)
                        viewModel.commentList.size.toString()
                    else "100+"
                /**/
                if (viewModel.commentList.size < 1) {
                    binding.apply {
                        articleEntityNoCommentView.visibility = View.VISIBLE
                        articleEntityRecyclerView.visibility = View.INVISIBLE
                        articleEntityEasyRefreshLayout.visibility = View.INVISIBLE
                    }
                } else {
                    binding.articleEntityNoCommentView.visibility = View.INVISIBLE
                    binding.articleEntityRecyclerView.visibility = View.VISIBLE
                    binding.articleEntityEasyRefreshLayout.visibility = View.VISIBLE
                }
            }
            commentText.observe(viewLifecycleOwner) {
                saveCommentById().observe(viewLifecycleOwner) {
                    if (it.success) {
                        addCommentList(
                            mutableListOf(
                                Comment(
                                    MyApplication.user!!.sfNumber,
                                    MyApplication.article!!.articleId,
                                    -1,
                                    commentText.value!!,
                                    LocalDateTime.now().toString()
                                )
                            )
                        )
                        binding.articleEntityRecyclerView.adapter?.notifyDataSetChanged()
                        binding.articleEntityCommentIconNumber.text =
                            if (binding.articleEntityCommentIconNumber.text.toString() == "100+" ||
                                binding.articleEntityCommentIconNumber.text.toString() == "100"
                            ) "100+"
                            else (binding.articleEntityCommentIconNumber.text.toString()
                                .toInt() + 1).toString()
                    } else {
                        CircleDialog.Builder().setText(it.message).setNegative("确定", null)
                            .show(parentFragmentManager)
                    }
                }
            }
        }
    }

    @SuppressLint("SetJavaScriptEnabled")
    private fun initWebView(u: String) {
        binding.articleEntityText.apply {
            //this.loadUrl(url)
            this.loadDataWithBaseURL(null, u, "text/html", "utf-8", null)
            //this.loadData(u, "text/html; charset=UTF-8", null)
            val webClient = object : WebViewClient() {
                override fun shouldOverrideUrlLoading(
                    view: WebView?,
                    request: WebResourceRequest?
                ): Boolean {
                    return true
                }

                @SuppressLint("WebViewClientOnReceivedSslError")
                override fun onReceivedSslError(
                    view: WebView?,
                    handler: SslErrorHandler?,
                    error: SslError?
                ) {
                    handler?.proceed()
                }

            }
            this.settings.apply {
                javaScriptEnabled = true  // 开启 JavaScript 交互
                domStorageEnabled = true
                blockNetworkImage = false // 禁止或允许WebView从网络上加载图片
                mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
                useWideViewPort = true
                allowFileAccess = true
                setSupportZoom(true)
                cacheMode = WebSettings.LOAD_NO_CACHE
                loadsImagesAutomatically = true // 支持自动加载图片
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    safeBrowsingEnabled = true // 是否开启安全模式
                }
                useWideViewPort = false  // 将图片调整到适合webview的大小
                loadWithOverviewMode = true  // 缩放至屏幕的大小
                domStorageEnabled = true
                webChromeClient = object : WebChromeClient() {}
            }
            this.webViewClient = webClient
            this.setLayerType(View.LAYER_TYPE_HARDWARE, null)
        }
    }

    /*
    * 点赞按钮点击监听器
    * */
    fun clickMyLove() {
        if (viewModel.isFabulous.value!!) {
            viewModel.cancelMyLove().observe(viewLifecycleOwner) {
                if (it.success) {
                    viewModel.updateFabulous(false)
                } else {
                    CircleDialog.Builder().setText(it.message).setNegative("确定", null)
                        .show(parentFragmentManager)
                }
            }
        } else {
            viewModel.saveMyLove().observe(viewLifecycleOwner) {
                if (it.success) {
                    viewModel.updateFabulous(true)
                } else {
                    CircleDialog.Builder().setText(it.message).setNegative("确定", null)
                        .show(parentFragmentManager)
                }
            }
        }
    }

    /*
    * 屏幕滚动到评论区
    * */
    fun toComment() {
        val behavior =
            (binding.articleEntityAppBarLayout.layoutParams as CoordinatorLayout.LayoutParams).behavior
        behavior?.let {
            behavior.onNestedPreScroll(
                binding.coordinatorLayout,
                binding.articleEntityAppBarLayout,
                binding.articleEntityExpressOpinionsLayout,
                0,
                binding.articleEntityExpressOpinionsLayout.top,
                intArrayOf(0, 0),
                TYPE_NON_TOUCH
            )
        }
        binding.articleEntityRecyclerView.apply {
            if (this.visibility == View.INVISIBLE) {
                binding.articleEntityAppBarLayout.setExpanded(true)
            } else {
                scrollToPosition(0)
            }
        }
    }

    /*
    * 收藏按钮监听器
    * */
    fun collect() {
        if (viewModel.isCollect.value!!) {
            viewModel.cancelCollectById().observe(viewLifecycleOwner) {
                if (it.success) {
                    viewModel.updateCollect(false)
                } else {
                    CircleDialog.Builder().setText(it.message).setNegative("确定", null)
                        .show(parentFragmentManager)
                }
            }
        } else {
            viewModel.saveCollectById().observe(viewLifecycleOwner) {
                if (it.success) {
                    viewModel.updateCollect(true)
                } else {
                    CircleDialog.Builder().setText(it.message).setNegative("确定", null)
                        .show(parentFragmentManager)
                }
            }
        }
    }

    /*
    * 弹出评论输入框，限制60个中文字符
    * */
    fun toInputComment() {
        CircleDialog.Builder().setInputText("", "请输入评论")
            .setInputHeight(Gravity.CENTER)
            .setInputCounter(60 * 3) { maxLen: Int, currentLen: Int ->
                "${(maxLen - currentLen) / 3} /${maxLen / 3}"
            }
            .setInputCounterColor(Color.BLACK).setInputShowKeyboard(true)
            .setPositiveInput("确定") { text, editText ->
                LogUtils.d(text)
                val set = MyApplication.filter.getSensitiveWord(text, 1)
                if (set.size == 0) {
                    viewModel.setCommentText(text)
                    binding.articleEntityEasyRefreshLayout.visibility = View.VISIBLE
                    binding.articleEntityRecyclerView.visibility = View.VISIBLE
                    binding.articleEntityNoCommentView.visibility = View.INVISIBLE
                } else {
                    LogUtils.e("语句中包含敏感词的个数为：" + set.size + "。包含：" + set)
                    CircleDialog.Builder().setText("本评论含有敏感词汇！").setNegative("重新输入", null)
                        .setTextColor(Color.RED)
                        .show(parentFragmentManager)
                }
                true
            }
            .setNegative("取消", null)
            .show(parentFragmentManager)
    }

    /*
    * 返回按监听器
    * */
    fun gotoBack() {
        if (MyApplication.navigateThing["ArticleEntity"] != null) {
            MyApplication.goto(
                MyApplication.navigateThing["ArticleEntity"]!!.toInt(),
                findNavController(),
                parentFragmentManager
            )
        } else {
            MyApplication.goto(
                R.id.action_ArticleEntity_to_Article,
                findNavController(),
                parentFragmentManager
            )
        }
    }

    private inner class CommentHolder(view: View) : RecyclerView.ViewHolder(view) {
        private lateinit var comment: Comment
        private val nameTextView =
            itemView.findViewById<TextView>(R.id.fragment_articleEntity_comment_Id)
        private val dateTextView =
            itemView.findViewById<TextView>(R.id.fragment_articleEntity_comment_time)
        private val contextView =
            itemView.findViewById<TextView>(R.id.fragment_articleEntity_comment_context)
        private val imageView =
            itemView.findViewById<ImageView>(R.id.fragment_articleEntity_avatars)

        @SuppressLint("SetTextI18n")
        fun bind(comment: Comment) {
            this.comment = comment
            nameTextView.text = this.comment.userSfNumber.toString()
            dateTextView.text = "${
                this.comment.commentTime.subSequence(
                    0,
                    10
                )
            } ${this.comment.commentTime.subSequence(11, 19)}"
            contextView.text = this.comment.commentContent
            MyApplication.setCircleGlideByUrlString(
                requireContext(),
                "http:120.53.123.145:8080/upload/noImage.jpg",
                imageView
            )
        }
    }

    private inner class CommentAdapter(var commentList: MutableList<Comment>) :
        RecyclerView.Adapter<CommentHolder>() {
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CommentHolder {
            val view = layoutInflater.inflate(R.layout.list_item_comment, parent, false)
            return CommentHolder(view)
        }

        override fun onBindViewHolder(holder: CommentHolder, position: Int) {
            val comment = commentList[position]
            LogUtils.e("我的位置：${position}")
            holder.bind(comment)
        }

        override fun getItemCount() = commentList.size

    }

    override fun onDestroy() {
        super.onDestroy()
        binding.articleEntityText.destroy()
    }
}